#include "SimplePlayer.h"
#include<stdio.h>

#include<QtMultimedia>

SimplePlayer::SimplePlayer(QObject *parent): QObject(parent){
	m_stoppedStateTimer = new QTimer(this);
	connect(m_stoppedStateTimer, SIGNAL(timeout()), this, SLOT(slotFinished()));
	m_stoppedStateTimer->setSingleShot(true);

	m_current.clear();
	m_state = Stopped;
	m_playerBackend = new QMediaPlayer(this);
	connect(m_playerBackend, SIGNAL(stateChanged(QMediaPlayer::State)), this, SLOT(slotStateChanged(QMediaPlayer::State)));

	printf("SimplePlayer created.\n");
}

SimplePlayer::~SimplePlayer(){
	printf("SimplePlayer deleted.\n");
}

void SimplePlayer::play(){
	printf("SimplePlayer::play()\t");
	if(m_state == Paused){
		m_playerBackend->play();
		printf("case 1\n");
	}else if (m_state == Stopped && !m_current.isEmpty()){
		printf("case 2\n");
		play(m_current);
	}
}

void SimplePlayer::play(QUrl location){
	m_current = location;
	m_playerBackend->stop();
	m_playerBackend->setMedia(location);
	m_state = Loading;
	m_playerBackend->play();
}

void SimplePlayer::pause(){
	m_playerBackend->pause();
}

void SimplePlayer::stop(){
	m_state = Loading;
	m_playerBackend->stop();
}

QUrl SimplePlayer::current()const{
	return m_current;
}

SimplePlayer::State SimplePlayer::state()const{
	return m_state;
}

void SimplePlayer::slotStateChanged(QMediaPlayer::State state){
	if(state == QMediaPlayer::StoppedState){
		m_state = Stopped;
		m_stoppedStateTimer->start(STOPPED_STATE_TIMEOUT);
	}else if(state == QMediaPlayer::PlayingState){
		m_state = Playing;
		m_stoppedStateTimer->stop();
	}else if(state == QMediaPlayer::PausedState){
		m_state = Paused;
		m_stoppedStateTimer->stop();
	}
}

void SimplePlayer::slotFinished(){
	emit finished(m_current);
}
